package com.jerry.boot.business.auth;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.jerry.boot.core.JConstant;
import com.jerry.boot.core.base.ApiException;
import com.jerry.boot.core.base.Channel;
import com.jerry.boot.core.base.ChannelCheckException;
import com.jerry.boot.core.web.ServletContextHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class AuthChannelValidator implements AuthValidator {
    @Override
    public void validate(HttpServletRequest request) throws ApiException {
        String chl = ServletUtil.getHeader(request, JConstant.CHL_HEADER_KEY, StandardCharsets.UTF_8);
        if (ServletContextHelper.isAjaxRequest(request)) {
            if (StrUtil.isBlank(chl)) {
                throw new ChannelCheckException("null");
            }
            Channel channel = null;
            try {
                channel = Channel.valueOf(chl);
            } catch (IllegalArgumentException e) {
                log.error("com.jerry.boot.business.auth.AuthChannelValidator.validate", e);
                throw new ChannelCheckException(chl);
            }
            channel.check(request);
        }
    }
}
